import React, { useState, useEffect } from 'react';
import { Card, Table, message, Modal, Input, Button, Space, Dropdown, Tooltip, Spin } from 'antd';
import { EditOutlined, DownOutlined, HomeOutlined, StopOutlined, DisconnectOutlined, ReloadOutlined, LoadingOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useNavigate, useLocation } from 'react-router-dom';
import DeviceDetailPage from './DeviceDetailPage';

const DeviceListPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const [devices, setDevices] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingDevice, setEditingDevice] = useState(null);
  const [newAlias, setNewAlias] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [unbindConfirmVisible, setUnbindConfirmVisible] = useState(false);
  const [showDetailOverlay, setShowDetailOverlay] = useState(false);
  const [selectedDeviceId, setSelectedDeviceId] = useState(null);
  const [loadingDeviceId, setLoadingDeviceId] = useState(null);

  // 获取URL参数
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const deviceId = searchParams.get('id');
    if (deviceId) {
      setSelectedDeviceId(deviceId);
      setShowDetailOverlay(true);
    } else {
      setShowDetailOverlay(false);
    }
  }, [location]);

  // 获取手机列表数据
  const fetchDevices = async () => {
    try {
      setLoading(true);
      const response = await axios.get('http://127.0.0.1:8081/user/device/list', {
        headers: {
          'token': localStorage.getItem('token')
        }
      });
      
      const { data } = response;
      if (data.data && data.data.devices) {
        // 按绑定时间降序排序
        const sortedDevices = [...data.data.devices].sort((a, b) => b.createTime - a.createTime);
        setDevices(sortedDevices);
      } else {
        setDevices([]);
      }
    } catch (error) {
      console.error('获取手机列表失败:', error);
      message.error('获取手机列表失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDevices();
  }, []);

  // 处理修改分组
  const handleEditAlias = (device) => {
    setEditingDevice(device);
    setNewAlias(device.alias || '');
    setEditModalVisible(true);
  };

  // 提交修改分组
  const handleSubmitAlias = async () => {
    if (!editingDevice) return;
    
    try {
      setSubmitting(true);
      
      const response = await axios.post(
        'http://127.0.0.1:8081/user/device/alias/change',
        { 
          newAlias,
          id: editingDevice.id  // 添加手机ID
        },
        {
          headers: {
            'token': localStorage.getItem('token'),
            'Content-Type': 'application/json'
          }
        }
      );
      
      const { data } = response;
      
      if (data.code) {
        // 修改失败
        message.error(data.msg);
      } else {
        // 修改成功
        message.success('分组修改成功');
        // 关闭模态框
        setEditModalVisible(false);
        // 更新本地数据
        const updatedDevices = devices.map(item => {
          if (item.id === editingDevice.id) {
            return { ...item, alias: newAlias };
          }
          return item;
        });
        setDevices(updatedDevices);
      }
    } catch (error) {
      console.error('修改分组失败:', error);
      message.error('修改分组失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  // 处理回到桌面
  const handleBackToDesktop = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先勾选手机');
      return;
    }
    message.info('回到桌面功能尚未实现');
  };

  // 处理停止任务
  const handleStopTask = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先勾选手机');
      return;
    }
    message.info('停止任务功能尚未实现');
  };

  // 处理解绑手机
  const handleUnbindDevice = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先勾选手机');
      return;
    }
    setUnbindConfirmVisible(true);
  };

  // 确认解绑手机
  const confirmUnbind = async () => {
    try {
      setSubmitting(true);
      
      // 这里假设一次只解绑一个手机，如果需要支持多个手机解绑，需要修改API调用逻辑
      const deviceId = selectedRowKeys[0];
      
      const response = await axios.post(
        'http://127.0.0.1:8081/user/device/unbind',
        { id: deviceId },
        {
          headers: {
            'token': localStorage.getItem('token'),
            'Content-Type': 'application/json'
          }
        }
      );
      
      const { data } = response;
      
      if (data.code) {
        // 解绑失败
        message.error(data.msg || '解绑失败');
      } else {
        // 解绑成功
        message.success('解绑成功');
        // 关闭确认框
        setUnbindConfirmVisible(false);
        // 重新获取手机列表
        fetchDevices();
        // 清空选择
        setSelectedRowKeys([]);
      }
    } catch (error) {
      console.error('解绑手机失败:', error);
      message.error('解绑手机失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  // 跳转到手机详情页
  const handleViewDeviceLog = (deviceId) => {
    setLoadingDeviceId(deviceId);
    
    // 生成200ms到1500ms之间的随机延迟时间
    const randomDelay = Math.floor(Math.random() * (1500 - 200 + 1)) + 200;
    
    setTimeout(() => {
      setSelectedDeviceId(deviceId);
      setLoadingDeviceId(null);
      navigate(`/device/list?id=${deviceId}`);
    }, randomDelay);
  };

  // 格式化时间戳
  const formatTimestamp = (timestamp) => {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  // 表格列定义
  const columns = [
    {
      title: '编号 / 昵称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      render: (name) => (
        <div style={{ 
          position: 'relative', 
          width: '100%',
          height: '32px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center'
        }}>
          <span>{name}</span>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'online',
      key: 'online',
      align: 'center',
      render: (online, record) => (
        <div>
          {online ? (
            <span 
              style={{ 
                color: '#1890ff', 
                cursor: 'pointer'
              }}
              onClick={() => handleViewDeviceLog(record.id)}
            >
              在线
            </span>
          ) : (
            <span style={{ color: '#999999' }}>
              离线
            </span>
          )}
        </div>
      ),
    },
    {
      title: '分组',
      dataIndex: 'alias',
      key: 'alias',
      align: 'center',
      render: (alias, record) => (
        <div>
          <span>{alias || '未分组'}</span>
          <EditOutlined 
            style={{ marginLeft: '10px', color: '#1890ff', cursor: 'pointer' }}
            onClick={() => handleEditAlias(record)}
          />
        </div>
      ),
    },
    {
      title: '分辨率',
      key: 'resolution',
      align: 'center',
      render: (_, record) => (
        <span>{record.width} x {record.height}</span>
      ),
    },
    {
      title: '品牌',
      dataIndex: 'brand',
      key: 'brand',
      align: 'center',
    },
    {
      title: '型号',
      dataIndex: 'model',
      key: 'model',
      align: 'center',
    },
    {
      title: '安卓版本',
      dataIndex: 'osVersion',
      key: 'osVersion',
      align: 'center',
    },
    {
      title: '绑定时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      render: (createTime) => formatTimestamp(createTime)
    },
  ];

  // 表格选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  // 操作菜单
  const items = [
    {
      key: 'unbind',
      icon: <DisconnectOutlined />,
      label: '解绑手机',
      onClick: handleUnbindDevice
    }
  ];

  return (
    <>
      <Spin 
        spinning={loadingDeviceId !== null}
        size="small"
      >
        <Card bordered={false} bodyStyle={{ padding: 0 }}>
          <div style={{ margin: '16px 16px', display: 'flex', justifyContent: 'space-between' }}>
            <Space size={15}>
              <Button 
                type="primary"
                icon={<ReloadOutlined />}
                onClick={fetchDevices}
              >
                刷新
              </Button>
              <Button 
                type="primary" 
                icon={<HomeOutlined />}
                onClick={handleBackToDesktop}
                style={{ backgroundColor: '#4cc83a', borderColor: '#4cc83a' }}
              >
                回到桌面
              </Button>
              <Button 
                type="primary" 
                danger
                icon={<StopOutlined />}
                onClick={handleStopTask}
              >
                停止任务
              </Button>
            </Space>
            <div>
              <Dropdown menu={{ items }}>
                <Button>
                  操作 <DownOutlined />
                </Button>
              </Dropdown>
            </div>
          </div>
          <div style={{ margin: '32px 16px 16px 16px' }}>
            <Table
              bordered
              rowSelection={rowSelection}
              columns={columns}
              dataSource={devices}
              rowKey="id"
              loading={loading}
              pagination={{ pageSize: 10 }}
            />
          </div>
          
          {/* 修改分组的模态框 */}
          <Modal
            title="修改分组"
            open={editModalVisible}
            onCancel={() => setEditModalVisible(false)}
            footer={[
              <Button key="cancel" onClick={() => setEditModalVisible(false)}>
                取消
              </Button>,
              <Button 
                key="submit" 
                type="primary" 
                loading={submitting} 
                onClick={handleSubmitAlias}
              >
                确定
              </Button>,
            ]}
          >
            <Input
              placeholder="请输入新的分组名称"
              value={newAlias}
              onChange={(e) => setNewAlias(e.target.value)}
              style={{ marginTop: 15, marginBottom: 15 }}
            />
          </Modal>
          
          {/* 解绑手机确认框 */}
          <Modal
            title="确认解绑"
            open={unbindConfirmVisible}
            onCancel={() => setUnbindConfirmVisible(false)}
            footer={[
              <Button key="cancel" onClick={() => setUnbindConfirmVisible(false)}>
                取消
              </Button>,
              <Button 
                key="submit" 
                type="primary" 
                danger
                loading={submitting} 
                onClick={confirmUnbind}
              >
                确定
              </Button>,
            ]}
          >
            <p>确定要解绑这些手机吗？</p>
          </Modal>
        </Card>
      </Spin>
      
      {/* 手机详情覆盖层 */}
      {showDetailOverlay && <DeviceDetailPage />}
    </>
  );
};

export default DeviceListPage; 